import { useEffect, useState, useRef } from 'react';
import { Skeleton, App } from 'antd';
import loadable from '@loadable/component';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';

import { HOME, WORK_DETAIL } from '@/config/url';
import { getKeyFromUrl } from '@/utils';
import { getWorkInfo, createWork, updateWork } from '@/service/api';

import styles from './index.module.scss';

const Form = loadable(() => import('./Form'));

export default props => {
    const initState = () => ({
        submitting: false,
    });
    const [state, setState] = useState(initState);
    const navigate = useNavigate();
    const { message } = App.useApp();
    const id = getKeyFromUrl('id');
    const formRef = useRef(null);

    // 编辑时初始化表单，新建时无用
    const initWork = async () => {
        if(!id) return formRef?.current?.resetFields();
        const [res, err] = await getWorkInfo({id});
        if(err) return message.error(err.message);

        const { seriesImages, mainSeriesImage, seriesName, seriesNameEn, author, contributingAuthor, publicationYear, searchNames } = res?.data || {};
        const imageList = (seriesImages||'').split(',').filter(Boolean);
        const images = { images: imageList, mainImage: mainSeriesImage };

        const formData = {
            seriesImages: images,
            seriesName,
            seriesNameEn,
            author,
            contributingAuthor,
            publicationYear: publicationYear ? dayjs(publicationYear) : null,
            searchNames: searchNames || [],
        };

        let t = setTimeout(() => {
            clearTimeout(t);

            formRef?.current?.setFieldsValue(formData);
        }, 100);
    };
    // 返回
    const goBack = () => {
        navigate(-1);
    };

    // 新建作品，新建成功后返回首页
    const onSubmit = async () => {
        if (state.submitting) return;
        
        formRef?.current?.validateFields().then(async values => {
            setState(o => ({ ...o, submitting: true }));
            
            try {
                const { searchNames, ...rest } = values;
                const seriesImages = values.seriesImages?.images?.join(',') || '';
                const mainSeriesImage = values.seriesImages?.mainImage || '';
                const postData = {
                    seriesImages: seriesImages || '',
                    mainSeriesImage: mainSeriesImage || '',
                    seriesName: values.seriesName || '',
                    seriesNameEn: values.seriesNameEn || '',
                    searchNames: Array.isArray(searchNames) ? searchNames : (searchNames || '').split(',').filter(Boolean),
                    author: values.author || '',
                    contributingAuthor: Array.isArray(values.contributingAuthor) ? values.contributingAuthor.join(',') : (values.contributingAuthor || ''),
                    publicationYear: values.publicationYear ? dayjs(values.publicationYear).format('YYYY') : '',
                    ...(id ? {id} : {}),
                };

                const api = id ? updateWork : createWork;
                const [response, err] = await api(postData);
                if (err) {
                    message.error(err.message);
                    return;
                }
                message.success(`${id ? '更新' : '创建'}成功`);
                navigate(`${WORK_DETAIL}?id=${id || response?.data?.id}`, {replace: true});
            } finally {
                setState(o => ({ ...o, submitting: false }));
            }
        });
    };

    useEffect(() => {
        initWork();
    }, []);

    return (
        <div className={styles['container']}>
            <Form
                onCancel={goBack}
                onOk={onSubmit}
                ref={formRef}
                submitting={state.submitting}
            />
        </div>
    )
}
